//
//  NewsInfoViewController.swift
//  TestWidget
//
//  Created by Clover on 2019/3/13.
//  Copyright © 2019 clover.com. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class NewsInfoViewController: UIViewController{
    private var tableview: UITableView!
    
    private var newsCell: NewsTableViewCell?
    
    var dataArr = [JSON]()
    
    //MARK: - life
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableview = UITableView()
        self.tableview.delegate = self;
        self.tableview.dataSource = self;
        self.tableview.clo_registerCell(cell: NewsTableViewCell.self)
        self.view.addSubview(self.tableview)
        self.autoLayout()
        self.getNewsInfo()
    }
    
    func autoLayout() {
        self.tableview.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    //MARK: - request
    func getNewsInfo() {
        Alamofire.request("https://api.apiopen.top/getTangPoetry?page=1&count=5").responseJSON { (response) in
            if let data = response.result.value {
                var json = JSON(data)
                self.dataArr = json["result"].array ?? [];
                print("json \(String(describing: self.dataArr))")
                self.tableview.reloadData()
            }
        }
    }
    //MARK: - Public Methods
    
    //MARK: - Private Methods
    
    //MARK: - Potocol
}

extension NewsInfoViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview!.clo_dequeueReusableCell(indexPath: indexPath) as NewsTableViewCell
        let json = self.dataArr[indexPath.row]
        cell.titleLbl.text = json["title"].stringValue
        cell.content.text = json["content"].stringValue
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let urlStr = String(format: "TestWidgetUrl://jumpvc?type=vc&index=%d", indexPath.row)
        self.extensionContext?.open(URL(string: urlStr)!, completionHandler: { (success) in
            print(success)
        })
    }
}
